<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户管理</title>
<jsp:include page="../inc.jsp"></jsp:include>
<script type="text/javascript"><!--
	Ext.onReady(function(){
		Ext.QuickTips.init();
		createGrid();
		createLayout();
		createForm();
		form = Ext.create('userForm');
	});
	
	var gridEl = 'repTime-grid';
	var grid, form, selModel, toolbar, searchFlds;
	var win;
	
	function createGrid(){
		var queryFlds = new Array();
		searchFlds = new Ext.util.MixedCollection();
		var fldTimeName = new Ext.form.TextField({
			name : 'loginName',
			id : gridEl + '-loginName',
			fieldLabel : '用户名',
			allowBlank : true,
			width : 200
		});

		searchFlds.add('loginName', fldTimeName);
		grid =	Ext.create('gridView',{
			remoteSort : true,
			gridId : gridEl,
			checkboxSelectionModel:true,
			queryFlds : queryFlds,
			searchFlds : searchFlds,
			entityClassName : 'com.rover.entity.system.User',
			queryUrl : '../userController/query.action',
			deleteUrl : '../userController/delete.action',
			jsonId : 'id',
			recordPk : [ "id" ]
		});
		selModel = grid.getSelectionModel();
		selModel.on('rowselect', onRowSelect);
	}
	
	// 选择某行
	function onRowSelect(selModel, rowIndex, record) {

	}
	
	// 刷新列表
	function reloadRecords() {
		grid.getStore().reload();
	}

	function createWindows() {
		if (win == null) {
			win = new Ext.Window({
				title : '新增',
				iconCls : 'icon-win',
				autoHeight : true,
				width : 335,
				height : 200,
				buttonAlign : 'center',
				buttons : [ {
					text : "保存",
					handler : function() {
						if (form.getForm().isValid()) {
							form.getForm().submit({
								url : '../userController/save.action',
								scope : form,
								success : function(form, action) {
									win.hide();
									grid.getStore().reload();
								},
								failure : function(form, action) {
									 if (action.result.message == undefined)
									      Ext.Msg.alert('错误', '网络连接失败.');
									    else
									      Ext.Msg.alert('错误', action.result.message);
								},
								waitMsg : '保存数据...'
							});
						} else {
							Ext.Msg.alert('提示', '表单含有无效或空数据');
						}
					},
					id : "btnSave"
				}, {
					text : "关闭",
					id : "btnClose",
					handler : function() {
						win.hide();
					}
				} ],
				layout : 'fit',
				plain : false,
				closable : false,
				modal : true,
				items : [ form ]
			});
		}
		win.show();
	}
	
	// 创建form表单
	function createForm() {
		Ext.define('userForm', {
			extend : 'Ext.form.Panel',
			fields : new Ext.util.MixedCollection(),
			initComponent : function() {
				var me = this;
				var tn = 1;

				this.fields.add("id", new Ext.form.Hidden({
					name : "id",
					dataIndex : "id"
				}));
				this.fields.add("loginName", new Ext.form.TextField({
					name : "loginName",
					dataIndex : "loginName",
					fieldLabel : "登录名",
					allowBlank : false
				//错误信息的显示
				}));
				this.fields.add("name", new Ext.form.TextField({
					name : "name",
					dataIndex : "name",
					fieldLabel : "用户姓名",
					allowBlank : false
				}));
				this.fields.add("email", new Ext.form.TextField({
					name : "email",
					dataIndex : "email",
					fieldLabel : "邮箱",
					allowBlank : true
				}));
				
				var roleStore = Ext.create('Ext.data.Store', {
			          fields : ['id', 'name'],
			          proxy : {
			        	    type: 'ajax',
			                url : '../roleController/getList.action',
			                reader: {
			                    type: 'json',
			                    root: 'rows'
			                }
			              },
							autoLoad: false
			        });
				roleStore.load();
				
				this.fields.add("rolesName", Ext.create('Ext.form.field.ComboBox', {
					id:'rolesName',
					name:'rolesName',
				    fieldLabel: '角色',
				    valueField: 'id',
				    displayField: 'name',
				    multiSelect:true,//多选
				    allowBlank : false,// 不允许为空
				    editable : false,// 是否允许输入
				    forceSelection : true,// 必须选择一个选项
				    blankText : '请选择',// 该项如果没有选择，则提示错误信息,
				    labelWidth: 130,
				    store: roleStore,
				    queryMode: 'local',
				    typeAhead: true,
				    listeners: {  
			            select: {  
			                scope: this,  
			                fn: function(combo, value, option) {  
    			                form.getForm().findField('rolesId').setValue(combo.getValue());
			                }  
			            }  
			        }  
				}));
				this.fields.add("rolesId", new Ext.form.Hidden({
					name : "rolesId",
					dataIndex : "rolesId"
				}));
				this.items = [ {
					layout : "form",
					columnWidth : 1,
					labelAlign : "right",
					labelWidth : 100,
					items : [ this.fields.get("id"), this.fields.get("loginName"),
					          this.fields.get("name"),this.fields.get("email"),
					          this.fields.get("rolesName"),this.fields.get("rolesId")]
				} ];
				this.frame = true;
				this.layout = 'fit';
				this.region = 'east';
				this.border = true;
				this.split = true;
				this.callParent(arguments);
			}
			,
			onRender : function() {
				this.callParent(arguments);
			},
			newDataRecord : function() {
				this.fields.get("id").setValue('');
				this.fields.get("loginName").setValue('');
				this.fields.get("name").setValue('');
				this.fields.get("email").setValue('');
			}
		});
	}

	// 新建或修改表单成功提交后,重新加载其父节点
	function afterCommitFormSuccess(operation, recordData) {
		onWinHide();
		grid.getStore().reload();
	}
	
	// 创建新的记录，初始化表单
	function EditRecord() {
		var sm = grid.getSelectionModel();
		var records = sm.getSelection();
		
		if (records.length <= 0) {
			Ext.Msg.alert('错误', "未选中记录，不能修改！");
			return;
		}
		var data = records[0].data;
		form.getForm().findField('id').setValue(data.id);
		form.getForm().findField('loginName').setValue(data.loginName);
		form.getForm().findField('name').setValue(data.name);
		form.getForm().findField('email').setValue(data.email);
		form.getForm().findField('rolesId').setValue(data.rolesId);
		//form.getForm().findField('rolesName').name=data.rolesName;
		form.getForm().findField('rolesName').setValue(data.rolesId);
		form.getForm().findField('rolesName').setRawValue(data.rolesName);
		createWindows();

	}
	
	//重置密码
	function InitPassword() {
		var sm = grid.getSelectionModel();
		var records = sm.getSelection();
		if (records.length <= 0) {
			Ext.Msg.alert('错误', "请先选中记录，再进行密码重置！");
			return;
		}else {
			var ids = records[0].data.id;
			for(var i=1;i<records.length;i++){
				ids = ids + ',' + records[i].data.id;
			}
			Ext.Ajax.request({
				url : '../userController/initPassword.action',
				method : 'post',
				params : {
					"ids" : ids
				},
				success : function() {
					Ext.Msg.alert('提示', '密码重置成功');
				}
			});
		}
	}
	
	//启用
	function Enable(){
		var sm = grid.getSelectionModel();
		var records = sm.getSelection();
		if (records.length <= 0) {
			Ext.Msg.alert('错误', "请先选中记录，再设置启用！");
			return;
		}else {
			var ids = records[0].data.id;
			for(var i=1;i<records.length;i++){
				ids = ids + ',' + records[i].data.id;
			}
			Ext.Ajax.request({
				url : "../userController/enable.action",
				method : "post",
				params : {"ids" : ids},
				success : function(){
					Ext.Msg.alert("提示","启用/禁用成功");
					grid.load();
				}
			});
		}
	}

	// 创建layout
	function createLayout() {
		toolbar = new Ext.Toolbar({
			items : [ {
				text : "新增",
				iconCls : 'addIcon',
				id : "tlb_NEW",
				handler : function() {
					form.newDataRecord();
					createWindows();
				}
			}, '-', {
				text : "编辑",
				iconCls : 'editIcon',
				id : "tlb_EDIT",
				handler : function() {
					EditRecord();
				}
			}, '-', {
				text : "删除",
				iconCls : 'deleteIcon',
				id : "tlb_DELETE",
				handler : function() {
					grid.deleteRecord();
				}
			}, '-', {
				text : "重置密码",
				id : "tlb_INIT",
				handler : function() {
					InitPassword();
				}
			},'-', {
				text : "启用/禁用",
				id : "tlb_JQ",
				handler : function() {
					Enable();
				}
			}, "->",  searchFlds.get("loginName"), {
		        text: "搜索",
		        iconCls : 'searchIcon',
		        handler: function () {
		        	grid.load();
		        }
		    } ]
		});

		var viewport = new Ext.Viewport({
			layout : 'border',
			items : [ {
				layout : 'fit',
				region : 'north',
				border : false,
				items : [ toolbar ],
				height : 25
			}, {
				layout : 'border',
				region : 'center',
				border : false,
				items : [ grid ]
			} ]
		});

		viewport.doLayout();
	}

</script>
</head>
<body>
</body>
</html>